# coding = gbk
# -*- coding:utf-8 -*-
import sys
import pandas as pd
import re

sys.path.append('/')
import os
from pathlib import Path
import accessControl
import utils
import tempfile
import json
from datetime import datetime
from openpyxl import Workbook


# import code_style_check_4ci

# 扫描函数
def runScan(path, gitcode_id, code_branch):
    '''
    :param path: 待扫描的md文件所在路径
    :return: 发现错误返回False和错误信息：resultDic；未发现错误返回True和"check success"
    '''
    # 用于记录扫描出的具体问题
    scanResult = []
    # 用于统计扫描出的各类问题数量
    fault_summary = {"owner_error": 0, "link_error": 0, "http_error": 0, "figure_lost": 0, "Chinese_in_English": 0,
                     "sample_code_error": 0, "文档一级标题错误": 0, "尖括号未转义": 0}
    # 用于保存所有数据，最后存到txt中
    resultDic = {"mdFiles": [], "scan_case_num": 7, "pass_case_num": 7, "fail_case_num": 0,
                 "fault_summary": fault_summary, "scanResult": []}

    mdFiles = utils.getMdFile(path)
    for mdFile in mdFiles:
        # 判断当前路径是文件还是文件夹，是文件的话直接处理
        if os.path.isdir(mdFile):
            directory_path = Path(mdFile)
            for file_path in directory_path.rglob('*.md'):
                print("正在检查文档:  "
                      "." + str(file_path))
                temp_path = get_temp_file(str(file_path))
                print(temp_path)
                check_item(temp_path, code_branch, scanResult, resultDic)
        elif os.path.isfile(mdFile):
            temp_path = get_temp_file(str(mdFile))
            print(temp_path)
            check_item(temp_path, code_branch, scanResult, resultDic)

    # code_style_check_4ci.sample_code_check(path, resultDic)
    mdFiles = utils.getMdFile(path)
    mdFilesPath = list(map(lambda mdFile: mdFile[mdFile.index('docs/'):], mdFiles))
    resultDic["mdFiles"] = mdFilesPath
    saveResult(resultDic)
    if resultDic["scanResult"]:
        # print(resultDic)
        return False, resultDic["scanResult"]
    return True, "check success"


# 保存扫描结果到本目录
def saveResult(resultDic):
    '''
    :param resultDic: 扫描结果保存字典
    '''
    # 保存到当前路径，获取后需要删除
    # if os.path.exists(os.path.join(os.path.realpath(os.path.dirname(__file__)), "check_result.txt")):
    #     os.remove(os.path.join(os.path.realpath(os.path.dirname(__file__)), "result.txt"))
    # savePath = os.path.join(os.path.realpath(os.path.dirname(__file__)), "result.txt")
    now = datetime.now()
    if os.path.exists(os.path.join(os.path.realpath(os.path.dirname(__file__)),
                                   '扫描结果' + now.strftime("%Y-%m-%d-%H-%M-%S") + '.xlsx')):
        os.remove(os.path.join(os.path.realpath(os.path.dirname(__file__)),
                               '扫描结果' + now.strftime("%Y-%m-%d-%H-%M-%S") + '.xlsx'))
    savePath = os.path.join(os.path.realpath(os.path.dirname(__file__)),
                            '扫描结果' + now.strftime("%Y-%m-%d-%H-%M-%S") + '.xlsx')
    try:
        #     # 加载工作簿
        #     wb = Workbook()
        #     # 激活工作表
        #     sheet = wb.active
        #     sheet.title = '检查结果'
        #     # if not os.path.exists(savePath):
        #     #     sheet['A1'] = '本地代码仓路径错误'
        #     #     wb.save(savePath)
        #     #     return
        #     sheet.append(
        #         ["文档路径", '错误类型', '错误信息', '处理结果'])
        #     # mdFiles = utils.getMdFile(path)
        #     # mdFilesPath = list(map(lambda mdFile: mdFile[mdFile.index('docs/'):], mdFiles))
        #     # resultDic["mdFiles"] = mdFilesPath
        #     scanResultList = resultDic["scanResult"]
        #     for scanResult in scanResultList:
        #         md_info_line = ['', '', '', '']
        #         file_path = scanResult["file"].replace('\\', '/')
        #         file_path = file_path[file_path.index('docs/'):]
        #         # print(file_path)
        #         md_info_line[0] = file_path
        #         md_info_line[1] = scanResult["error_type"]
        #         md_info_line[2] = scanResult["error_info"]
        #         sheet.append(md_info_line)
        #     wb.save(savePath)

        scanResultList = resultDic["scanResult"]
        md_info_line_list = []
        for scanResult in scanResultList:
            md_info_line = ['', '', '', '', '', '']
            file_path = scanResult["file"].replace('\\', '/')
            file_path = file_path[file_path.index('docs/'):]
            # D:\project\gitCode-test\
            file_path_read = 'D:\project\gitCode-test\\' + file_path
            file_path_read = file_path_read.replace('\\', '/')
            kit_string = "common"
            subsystem_string = "common"
            with open(file_path_read, 'r', encoding='utf-8', errors='ignore') as mdfile:
                file_content = mdfile.read()
                pattern_kit = f'<!--Kit:(.*?)-->\n'
                match_kit = re.search(pattern_kit, file_content)

                if match_kit:
                    kit_string = match_kit.group(1).lstrip()
                pattern_subsystem = f'<!--Subsystem:(.*?)-->\n'
                match_subsystem = re.search(pattern_kit, file_content)

                if match_subsystem:
                    subsystem_string = match_kit.group(1).lstrip()

            # print(file_path)
            md_info_line[0] = file_path
            md_info_line[1] = kit_string
            md_info_line[2] = subsystem_string
            md_info_line[3] = scanResult["error_type"]
            md_info_line[4] = scanResult["error_info"]
            md_info_line_list.append(md_info_line)
        # print(md_info_line_list)
        pd.DataFrame(md_info_line_list,
                     columns=["文档路径", "kit", "子系统", '错误类型', '错误信息', '处理结果']).to_excel(savePath,
                                                                                                         index=False)
    except FileNotFoundError as e:
        print(e)


# 待检测项目
def check_item(path, code_branch, scanResult, resultDic):
    # accessControl.permission_check(path,gitcode_id, scanResult, resultDic)
    # accessControl.owner_lost(path, code_branch, scanResult, resultDic)
    # accessControl.figureLost(path, scanResult, resultDic)
    # accessControl.relaLinkErrorNew(path, scanResult, resultDic)
    accessControl.mdStyleCheck(path, scanResult, resultDic)
    # accessControl.httpError(path,scanResult,resultDic)
    # accessControl.findCN(path, scanResult, resultDic)
    # accessControl.checkTitle(path, scanResult, resultDic)
    # accessControl.get_untranfered_angle_brackets(path, scanResult, resultDic)


# 获取路径对应的临时文件
def get_temp_file(mdFile):
    with tempfile.NamedTemporaryFile(mode='w+', delete=False) as tempFile:
        tempFile.write(mdFile)
        # 返回临时文件的路径
        return tempFile.name


if __name__ == "__main__":
    # 传入txt文件路径
    # path = sys.argv[1]
    path = r'D:\project\personal_project\person_check\access-control\result\master误报.txt'
    gitcode_id = '@albee1213'
    code_branch = 'master'
    runScan(path, gitcode_id, code_branch)
    print("Finish!")
